<template>
  <svg 
    ref="svgRef" 
    :width="width" 
    :height="height" 
    class="galaxy-force-tree"
    :class="galaxyCore.store.theme"
    @contextmenu="handleSvgContextMenu"
  ></svg>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import galaxyCore from '../index';

const svgRef = ref(null);
const width = ref(0);
const height = ref(0);

// 监听尺寸变化
const resizeObserver = new ResizeObserver(entries => {
  if (entries[0]) {
    const { width: w, height: h } = entries[0].contentRect;
    width.value = w;
    height.value = h;
    galaxyCore.resize(w, h);
  }
});

// 处理SVG右键菜单
const handleSvgContextMenu = (e) => {
  if (!e.target.closest('.node')) {
    galaxyCore.emit('contextmenu', e, null);
  }
};

onMounted(() => {
  if (svgRef.value) {
    // 初始化尺寸
    const { clientWidth, clientHeight } = svgRef.value.parentElement;
    width.value = clientWidth;
    height.value = clientHeight;
    
    // 初始化核心组件
    galaxyCore.initialize(svgRef.value, width.value, height.value);
    
    // 监听更新事件
    galaxyCore.on('update', () => {
      galaxyCore.update(svgRef.value);
    });
    
    // 监听主题变化
    galaxyCore.on('theme-change', (newTheme) => {
      updateThemeStyles();
    });
    
    // 监听右键菜单事件
    galaxyCore.on('contextmenu', (e, node) => {
      galaxyCore.emit('show-contextmenu', e, node);
    });
    
    // 监听尺寸变化
    resizeObserver.observe(svgRef.value.parentElement);
  }
});

// 更新主题样式
const updateThemeStyles = () => {
  if (!svgRef.value) return;
  
  const svg = galaxyCore.d3?.select(svgRef.value);
  if (!svg) return;
  const nodes = svg.selectAll('.node circle');
  const labels = svg.selectAll('.node text');
  const links = svg.selectAll('.links line');
  
  if (galaxyCore.store.theme === 'light') {
    nodes.attr('stroke', '#333');
    labels.attr('fill', '#333');
    links.attr('stroke', d => galaxyCore.colorScale(d.source.colorGroup)?.darker(2));
  } else {
    nodes.attr('stroke', '#fff');
    labels.attr('fill', '#fff');
    links.attr('stroke', d => galaxyCore.colorScale(d.source.colorGroup));
  }
};

onUnmounted(() => {
  resizeObserver.disconnect();
  if (galaxyCore.simulation) {
    galaxyCore.simulation.stop();
  }
});
</script>

<style scoped>
.galaxy-force-tree {
  cursor: grab;
  width: 100%;
  height: 100%;
}

.galaxy-force-tree:active {
  cursor: grabbing;
}

.galaxy-force-tree.light {
  background: radial-gradient(#f5f5f5, #ffffff);
}

.galaxy-force-tree.dark {
  background: radial-gradient(#111, #000);
}
</style>